import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

/// 图片缓存
class CachedImage extends StatelessWidget {
  final String imageUrl;
  final bool circle;
  final double? width;
  final double? height;
  final BoxFit fit;

  const CachedImage(
      {Key? key,
      required this.imageUrl,
      this.circle = false,
      this.width,
      this.height,
      this.fit = BoxFit.cover})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: height,
      child: circle ? _buildCircle() : _buildRectangle(),
    );
  }

  _buildCircle() {
    return ClipOval(
      child: _buildImage(),
    );
  }

  _buildRectangle() {
    return Container(
      child: _buildImage(),
    );
  }

  _buildImage() {
    return _fromNetwork()
        ? CachedNetworkImage(
            imageUrl: imageUrl,
            width: width,
            height: height,
            fit: fit,
            placeholder: (context, url) => Container(
              child: Center(
                child: CircularProgressIndicator(),
              ),
              width: width,
              height: height,
            ),
            errorWidget: (context, url, error) => new Icon(Icons.error),
          )
        : Image.asset(
            imageUrl,
            fit: BoxFit.fill,
          );
  }

  bool _fromNetwork() {
    return imageUrl.startsWith('http');
  }
}
